<template>
  <div class="log-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="操作类型">
          <el-select v-model="searchForm.operationType" placeholder="请选择操作类型" clearable>
            <el-option label="登录" value="login" />
            <el-option label="登出" value="logout" />
            <el-option label="新增" value="add" />
            <el-option label="修改" value="update" />
            <el-option label="删除" value="delete" />
            <el-option label="导出" value="export" />
            <el-option label="导入" value="import" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="成功" value="success" />
            <el-option label="失败" value="fail" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model="searchForm.operator" placeholder="请输入操作人" clearable />
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="table-operations">
        <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
          <el-icon><Delete /></el-icon> 批量删除
        </el-button>
        <el-button type="info" @click="handleClean">
          <el-icon><DeleteFilled /></el-icon> 清空日志
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon> 导出Excel
        </el-button>
      </div>

      <el-table
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="module" label="功能模块" width="120" />
        <el-table-column prop="operationType" label="操作类型" width="100">
          <template #default="scope">
            <el-tag
              :type="getOperationTypeColor(scope.row.operationType)"
            >
              {{ getOperationTypeText(scope.row.operationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operation" label="操作内容" min-width="150" show-overflow-tooltip />
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column prop="operatorIp" label="操作IP" width="130" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
              {{ scope.row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operationTime" label="操作时间" width="180" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" link @click="handleDetail(scope.row)">
              <el-icon><InfoFilled /></el-icon> 详情
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      title="日志详情"
      v-model="detailDialogVisible"
      width="700px"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="操作模块">{{ currentLog.module }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag :type="getOperationTypeColor(currentLog.operationType)">
            {{ getOperationTypeText(currentLog.operationType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作人">{{ currentLog.operator }}</el-descriptions-item>
        <el-descriptions-item label="操作IP">{{ currentLog.operatorIp }}</el-descriptions-item>
        <el-descriptions-item label="操作地点">{{ currentLog.location }}</el-descriptions-item>
        <el-descriptions-item label="操作状态">
          <el-tag :type="currentLog.status === 'success' ? 'success' : 'danger'">
            {{ currentLog.status === 'success' ? '成功' : '失败' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ currentLog.operationTime }}</el-descriptions-item>
        <el-descriptions-item label="客户端">{{ currentLog.userAgent }}</el-descriptions-item>
        <el-descriptions-item label="操作内容" :span="2">{{ currentLog.operation }}</el-descriptions-item>
        <el-descriptions-item v-if="currentLog.params" label="请求参数" :span="2">
          <el-input
            type="textarea"
            :rows="3"
            v-model="currentLog.params"
            readonly
          />
        </el-descriptions-item>
        <el-descriptions-item v-if="currentLog.errorMsg" label="错误信息" :span="2">
          <el-input
            type="textarea"
            :rows="3"
            v-model="currentLog.errorMsg"
            readonly
          />
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  Search,
  Refresh,
  Delete,
  DeleteFilled,
  Download,
  InfoFilled
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  operationType: '',
  status: '',
  operator: '',
  dateRange: []
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 日志详情对话框
const detailDialogVisible = ref(false)
const currentLog = ref({})

// 操作类型文本映射
const getOperationTypeText = (type) => {
  const map = {
    login: '登录',
    logout: '登出',
    add: '新增',
    update: '修改',
    delete: '删除',
    export: '导出',
    import: '导入',
    other: '其他'
  }
  return map[type] || type
}

// 操作类型颜色映射
const getOperationTypeColor = (type) => {
  const map = {
    login: 'success',
    logout: 'info',
    add: 'primary',
    update: 'warning',
    delete: 'danger',
    export: 'success',
    import: 'warning',
    other: 'info'
  }
  return map[type] || 'info'
}

// 获取日志列表
const getLogList = () => {
  loading.value = true
  // 实际项目中这里会调用后端API
  setTimeout(() => {
    // 模拟数据
    const mockLogs = []
    const operations = [
      { type: 'login', content: '用户登录' },
      { type: 'logout', content: '用户登出' },
      { type: 'add', content: '新增用户数据' },
      { type: 'update', content: '修改用户信息' },
      { type: 'delete', content: '删除用户记录' },
      { type: 'export', content: '导出用户数据' },
      { type: 'import', content: '导入用户数据' }
    ]

    const modules = ['用户管理', '角色管理', '权限管理', '系统设置', '数据字典']
    const userNames = ['admin', '张三', '李四', '王五', '赵六']
    const ips = ['192.168.1.1', '10.0.0.1', '172.16.0.1', '127.0.0.1']
    const userAgents = [
      'Chrome/90.0.4430.212',
      'Firefox/88.0',
      'Safari/14.1',
      'Edge/90.0.818.62'
    ]

    for (let i = 1; i <= 100; i++) {
      const operation = operations[Math.floor(Math.random() * operations.length)]
      const status = Math.random() > 0.1 ? 'success' : 'fail' // 10% 失败率

      mockLogs.push({
        id: i,
        module: modules[Math.floor(Math.random() * modules.length)],
        operationType: operation.type,
        operation: operation.content,
        operator: userNames[Math.floor(Math.random() * userNames.length)],
        operatorIp: ips[Math.floor(Math.random() * ips.length)],
        status,
        operationTime: `2023-10-${Math.floor(Math.random() * 30) + 1} ${Math.floor(Math.random() * 24)}:${Math.floor(Math.random() * 60)}:${Math.floor(Math.random() * 60)}`,
        location: '北京市海淀区',
        userAgent: userAgents[Math.floor(Math.random() * userAgents.length)],
        params: status === 'success' ? JSON.stringify({ id: 1, name: '测试' }) : null,
        errorMsg: status === 'fail' ? '操作失败，权限不足' : null
      })
    }

    // 筛选处理
    let filteredLogs = [...mockLogs]

    if (searchForm.operationType) {
      filteredLogs = filteredLogs.filter(log => log.operationType === searchForm.operationType)
    }

    if (searchForm.status) {
      filteredLogs = filteredLogs.filter(log => log.status === searchForm.status)
    }

    if (searchForm.operator) {
      filteredLogs = filteredLogs.filter(log => log.operator.includes(searchForm.operator))
    }

    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      const startTime = new Date(searchForm.dateRange[0]).getTime()
      const endTime = new Date(searchForm.dateRange[1]).getTime()

      filteredLogs = filteredLogs.filter(log => {
        const logTime = new Date(log.operationTime).getTime()
        return logTime >= startTime && logTime <= endTime
      })
    }

    // 分页处理
    pagination.total = filteredLogs.length
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize

    tableData.value = filteredLogs.slice(start, end)
    loading.value = false
  }, 500)
}

// 初始化数据
onMounted(() => {
  getLogList()
})

// 选择行变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  getLogList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'dateRange' ? [] : ''
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  getLogList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  getLogList()
}

// 查看详情
const handleDetail = (row) => {
  currentLog.value = row
  detailDialogVisible.value = true
}

// 删除日志
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除ID为${row.id}的日志记录吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际项目中这里会调用删除API
    ElMessage.success('删除成功')
    getLogList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的${selectedRows.value.length}条日志记录吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际项目中这里会调用批量删除API
    ElMessage.success('批量删除成功')
    getLogList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 清空日志
const handleClean = () => {
  ElMessageBox.confirm(
    '确定要清空所有日志记录吗？此操作不可逆！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际项目中这里会调用清空API
    ElMessage.success('日志清空成功')
    getLogList()
  }).catch(() => {
    ElMessage.info('已取消清空')
  })
}

// 导出Excel
const handleExport = () => {
  ElMessage.success('导出成功')
}
</script>

<style scoped>
.log-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
